<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="批次标题" prop="bitchName">
        <el-input v-model="queryParams.bitchName" placeholder="请输入批次名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="所属工区" prop="space">
        <!-- <el-input v-model="queryParams.space" placeholder="请输入所属工区" clearable @keyup.enter.native="handleQuery" /> -->
        <el-select v-model="queryParams.space" placeholder="所属岗位">
          <el-option v-for="item in dict.type.space" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="所属岗位" prop="sysPost">
        <!-- <el-input v-model="queryParams.sysPost" placeholder="请输入所属岗位" clearable @keyup.enter.native="handleQuery" /> -->
        <el-select v-model="queryParams.sysPost" placeholder="所属岗位">
          <el-option v-for="item in postOptions" :key="item.postId" :label="item.postName" :value="item.postId"
            :disabled="item.status == 1">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="开始时间" prop="startTime">
        <el-date-picker clearable v-model="queryParams.startTime" type="date" value-format="yyyy-MM-dd"
          placeholder="请选择开始时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="结束时间" prop="endTime">
        <el-date-picker clearable v-model="queryParams.endTime" type="date" value-format="yyyy-MM-dd"
          placeholder="请选择结束时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="试卷" prop="parperId">
        <!-- <el-input v-model="queryParams.parperId" placeholder="请输入试卷ID" clearable @keyup.enter.native="handleQuery" /> -->
        <el-select v-model="queryParams.parperId" placeholder="请选择试卷">
          <el-option v-for="item in parperList" :key="item.id" :label="item.parperName" :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['exa:bitch:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['exa:bitch:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['exa:bitch:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['exa:bitch:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="bitchList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" align="center" prop="id" />
      <el-table-column label="批次标题" align="center" prop="bitchName" />
      <el-table-column label="所属工区" align="center" prop="spaceName" />
      <el-table-column label="所属岗位" align="center" prop="sysPostName" />
      <el-table-column label="开始时间" align="center" prop="startTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.startTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="结束时间" align="center" prop="endTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.endTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="试卷" align="center" prop="parperName" />
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <span v-if="scope.row.status == 0" style="color: #999;">未开始</span>
          <span v-else-if="scope.row.status == 1" style="color: #4D4D4D;">已结束</span>
          <span v-else-if="scope.row.status == 2" style="color: #5AD447;">进行中</span>
        </template>

      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="200">
        <template slot-scope="scope">
          <div style="display: flex; justify-content: flex-start;">

            <el-button size="small" type="primary" plain @click="handleView(scope.row)">查看</el-button>

            <el-button v-if="scope.row.status == 2" v-hasPermi="['exa:bitch:edit']" size="small" type="primary" plain
              @click="handleRecycle(scope.row)">回收</el-button>


            <el-button v-if="scope.row.status == 1" size="small" type="primary" plain
              @click="handleResult(scope.row)">结果</el-button>


            <el-button v-if="scope.row.status == 0" size="small" type="primary" plain @click="handleUpdate(scope.row)"
              v-hasPermi="['exa:bitch:edit']">修改</el-button>

            <el-button v-if="scope.row.status != 2" size="small" type="danger" plain @click="handleDelete(scope.row)"
              v-hasPermi="['exa:bitch:remove']">删除</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改考试批次对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">

        <el-row>
          <el-col :span="24">
            <el-form-item label="批次标题" prop="bitchName">
              <el-input v-model="form.bitchName" placeholder="请输入批次名称" :disabled="dialogMode === 'view'" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="所属工区" prop="space">
              <!-- <treeselect v-model="form.space" :options="enabledDeptOptions" :show-count="true" placeholder="归属工区" /> -->
              <el-select v-model="form.space" placeholder="所属岗位" :disabled="dialogMode === 'view'">
                <el-option v-for="item in dict.type.space" :key="item.value" :label="item.label" :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="所属岗位" prop="sysPost">
              <el-select v-model="form.sysPost" placeholder="所属岗位" :disabled="dialogMode === 'view'">
                <el-option v-for="item in postOptions" :key="item.postId" :label="item.postName" :value="item.postId"
                  :disabled="item.status == 1">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="开始时间" prop="startTime">
              <el-date-picker clearable v-model="form.startTime" type="date" value-format="yyyy-MM-dd"
                placeholder="请选择开始时间" :disabled="dialogMode === 'view'">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="结束时间" prop="endTime">
              <el-date-picker clearable v-model="form.endTime" type="date" value-format="yyyy-MM-dd"
                placeholder="请选择结束时间" :disabled="dialogMode === 'view'">

              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="试卷" prop="parperId">
              <!-- <el-input v-model="form.parperId" placeholder="请输入试卷ID" /> -->
              <el-select v-model="form.parperId" placeholder="请选择试卷" :disabled="dialogMode === 'view'">
                <el-option v-for="item in parperList" :key="item.id" :label="item.parperName" :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" :rows="3"
            :disabled="dialogMode === 'view'" />

        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" v-if="dialogMode !== 'view'">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { listBitch, getBitch, delBitch, addBitch, updateBitch, recycleBitch } from "@/api/exa/bitch"
import { getUser } from "@/api/system/user"
import { listParper } from "@/api/exa/parper"

import Treeselect from "@riophae/vue-treeselect"
import "@riophae/vue-treeselect/dist/vue-treeselect.css"

export default {
  components: { Treeselect },
  dicts: ["space"],
  name: "Bitch",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 考试批次表格数据
      bitchList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        bitchName: null,
        space: null,
        sysPost: null,
        startTime: null,
        endTime: null,
        parperId: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        bitchName: [
          { required: true, message: "请输入批次名称", trigger: "blur" },
          // { min: 2, max: 20, message: "长度在 2 到 20 个字符", trigger: "blur" }
        ],
        space: [
          { required: true, message: "请选择所属工区", trigger: "change" }
        ],
        sysPost: [
          { required: true, message: "请选择所属岗位", trigger: "change" }
        ],
        startTime: [
          { required: true, message: "请选择开始时间", trigger: "change" }
        ],
        endTime: [
          { required: true, message: "请选择结束时间", trigger: "change" }
        ],
        parperId: [
          { required: true, message: "请选择试卷", trigger: "change" }
        ],
        remark: [
          { max: 200, message: "长度不能超过200个字符", trigger: "blur" }
        ]
      },
      // 岗位下拉选项
      postOptions: [],
      // 试卷下拉选项
      parperList: [],
      dialogMode: 'edit', // 可选值：'view'（查看）、'add'（添加）、'edit'（修改）
    }
  },
  created() {
    this.getList();
    this.getParPerList();
    this.getUserList();
  },
  methods: {
    /** 查询考试批次列表 */
    getList() {
      this.loading = true
      listBitch(this.queryParams).then(response => {
        this.bitchList = response.rows
        this.total = response.total
        this.loading = false
      })
    },

    // 获取岗位列表
    getUserList() {
      getUser().then(response => {
        this.postOptions = response.posts
      })
    },

    // 获取试卷列表
    getParPerList() {
      this.loading = true
      let obj = {
        pageNum: 1,
        pageSize: 999999999,
      }
      listParper(obj).then(response => {
        console.log("试卷列表", response);

        this.parperList = response.rows
      })
    },

    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },

    // 回收按钮
    handleRecycle(row) {
      const id = row.id || this.ids
      this.$modal.confirm('是否确认回收？').then(function () {
        return recycleBitch(id)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("回收成功")
      }).catch(() => {
        this.$modal.msgError("回收失败")
      })
    },

    // 结果按钮
    handleResult(row) {
      console.log("结果:", row);

      let params = {
        id: row.id,
        sysPost: row.sysPost,
        space: row.space,

      }
      // 路由跳转传参
      this.$router.push({
        path: '/parper/exaResult',
        query: params
      })


      // listExaResult(this.queryParams2).then(response => {
      //   console.log("考试结果列表", response);
      // })

    },


    // 表单重置
    reset() {
      this.form = {
        id: null,
        bitchName: null,
        space: null,
        sysPost: null,
        startTime: null,
        endTime: null,
        parperId: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      }
      this.resetForm("form")
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },

    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },

    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加考试批次"
      this.dialogMode = 'add'
    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getBitch(id).then(response => {
        response.data.sysPost = Number(response.data.sysPost)
        this.form = response.data
        this.open = true
        this.title = "修改考试批次"
        this.dialogMode = 'edit'
      })
    },

    /** 查看按钮操作 */
    handleView(row) {
      this.reset()
      const id = row.id || this.ids
      getBitch(id).then(response => {
        response.data.sysPost = Number(response.data.sysPost)
        this.form = response.data
        this.open = true
        this.title = "查看考试批次"
        this.dialogMode = 'view'
      })
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateBitch(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addBitch(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除考试批次编号为"' + ids + '"的数据项？').then(function () {
        return delBitch(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => { })
    },

    /** 导出按钮操作 */
    handleExport() {
      this.download('exa/bitch/export', {
        ...this.queryParams
      }, `bitch_${new Date().getTime()}.xlsx`)
    }
  }
}
</script>
